<?php
/**
 * 微信登录 - 获取授权URL
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// 读取配置
$config = include __DIR__ . '/../../config.php';
$wechatConfig = $config['plugins']['wechat'] ?? [];

if (empty($wechatConfig['enabled']) || !$wechatConfig['enabled']) {
    echo json_encode(['success' => false, 'message' => '微信登录服务未启用']);
    exit;
}

// 验证配置完整性
$requiredFields = ['app_id', 'app_secret', 'redirect_uri'];
foreach ($requiredFields as $field) {
    if (empty($wechatConfig[$field])) {
        echo json_encode(['success' => false, 'message' => '微信登录配置不完整']);
        exit;
    }
}

// 生成state参数用于防CSRF
$state = md5(uniqid(rand(), true));
$_SESSION['wechat_state'] = $state;

// 构造微信授权URL
$authUrl = 'https://open.weixin.qq.com/connect/qrconnect?' . http_build_query([
    'appid' => $wechatConfig['app_id'],
    'redirect_uri' => urlencode($wechatConfig['redirect_uri']),
    'response_type' => 'code',
    'scope' => 'snsapi_login',
    'state' => $state
]) . '#wechat_redirect';

echo json_encode([
    'success' => true,
    'auth_url' => $authUrl
]);
